using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.Web.Services;

public partial class BuySell : System.Web.UI.Page
{
    string current_username; //testing user
    int current_gameid;

    string current_connectionString = "stockmarketConnectionString";

    //default page load
    protected void Page_Load(object sender, EventArgs e)
    {
        //Added by CL
        if (!HttpContext.Current.Request.IsAuthenticated)
        {
            Response.Redirect("~/login.aspx");
        }
        else
        {
            if ((string)Session["GameID"] == "-1")
                Response.Redirect("~/GameMode.aspx");

            else
            {
                //Added by CL
                if (!ClientScript.IsStartupScriptRegistered("graph"))
                {
                    Page.ClientScript.RegisterStartupScript(this.GetType(), "graph", "drawGraph();", true);
                }

                current_gameid = Int32.Parse((string)Session["GameID"]);
                current_username = (string)Session["UserName"];

                double userCashOnHand = 0;
                double totalUserStockAmt = 0;

                GridView_UserExistingStock.RowCommand += new GridViewCommandEventHandler(GridView_UserExistingStock_RowCommand);
                GridView_SellStock.RowCommand += new GridViewCommandEventHandler(GridView_SellStock_RowCommand);
                GridView_EditTPSL.RowUpdated += new GridViewUpdatedEventHandler(GridView_EditTPSL_RowUpdated);

                SqlConnection buysell_con = new SqlConnection(ConfigurationManager.ConnectionStrings[current_connectionString].ConnectionString);

                SqlCommand cmdRetrieveCashOnHand = new SqlCommand("SELECT AccountAmount FROM [User] WHERE UserName = @current_user", buysell_con);
                cmdRetrieveCashOnHand.Parameters.Add("@current_user", SqlDbType.VarChar).Value = current_username;

                SqlCommand cmdTotalUserStockAmt = new SqlCommand("SELECT UserCurrentStock.ShareQuantity, ShareSimulation.CloseValue " +
                                                                  "FROM Game INNER JOIN ShareSimulation ON Game.GameID = ShareSimulation.GameID " +
                                                                  "AND Game.GameElapsedDate = ShareSimulation.HistoryDate INNER JOIN UserCurrentStock ON ShareSimulation.GameID = UserCurrentStock.GameID " +
                                                                  "AND ShareSimulation.ShareSymbol = UserCurrentStock.ShareName WHERE (UserCurrentStock.UserName = @current_user) AND (ShareSimulation.GameID = @gameid)", buysell_con);
       
                cmdTotalUserStockAmt.Parameters.Add("@gameid", SqlDbType.Int).Value = current_gameid;
                cmdTotalUserStockAmt.Parameters.Add("@current_user", SqlDbType.VarChar).Value = current_username;

                buysell_con.Open();
                cmdRetrieveCashOnHand.ExecuteNonQuery();
                SqlDataReader myCashReader = cmdRetrieveCashOnHand.ExecuteReader();
                while (myCashReader.Read())
                {
                    userCashOnHand = double.Parse(myCashReader["AccountAmount"].ToString());
                }
                buysell_con.Close();

                buysell_con.Open();
                cmdTotalUserStockAmt.ExecuteNonQuery();
                SqlDataReader myTotalUserStockAmt = cmdTotalUserStockAmt.ExecuteReader();

                while (myTotalUserStockAmt.Read())
                {
                    totalUserStockAmt += (Int32.Parse(myTotalUserStockAmt["ShareQuantity"].ToString()) * double.Parse(myTotalUserStockAmt["CloseValue"].ToString()));
                }
                buysell_con.Close();

                lblCashOnHand.Text = Convert.ToString(userCashOnHand);
                lblTotalNetworth.Text = Convert.ToString(userCashOnHand + totalUserStockAmt);
                lblFloatingPL.Text = Convert.ToString(totalUserStockAmt);

            }
        }

        bindgrid_Transaction();
    }

    //Buy button for what are the available stock in the current game
    protected void btn_BuyAvailable_Click(object sender, EventArgs e)
    {
        if (!ClientScript.IsStartupScriptRegistered("graph"))
        {
            Page.ClientScript.RegisterStartupScript(this.GetType(), "graph", "drawGraph();", true);
        }

        double current_MarketShareValue;
        string current_TransactionType = "BUY";

        string current_ShareSymbol = ShareCompanyDropdown.SelectedValue;
        int current_ID = 0;

        double current_TP = -1;
        double current_SL = -1;

        bool successfulTransac = false;

        //get and validate live rates existence.
        if (!double.TryParse(lblRates.Text, out current_MarketShareValue))
        {
            ScriptManager.RegisterStartupScript(this, GetType(), "error", "alert('Unable to buy please contact Administrator.');", true);
            return;
        }

        //validate TP
        if (validateValue(txtBuyTP.Text.ToString()))
        {
            double.TryParse(txtBuyTP.Text.ToString(), out current_TP);
            
            if (current_TP < current_MarketShareValue) //TP must be above buying price for a valid T/P
            {
                ScriptManager.RegisterStartupScript(this, GetType(), "error", "alert('T/P must be more than the buying price.');", true);
                return;
            }
        }
        else //if (validateValue(txtBuyTP.Text))
        {
            if (txtBuyTP.Text.ToString() != string.Empty)
            {
                ScriptManager.RegisterStartupScript(this, GetType(), "error", "alert('Only positive numbers allowed in T/P!');", true);
                return;
            }
        }

        //validate SL
        if (validateValue(txtBuySL.Text.ToString()))
        {
            double.TryParse(txtBuySL.Text.ToString(), out current_SL);
            
            if (current_SL > current_MarketShareValue) //SL must be below selling price for a valid S/L
            {
                ScriptManager.RegisterStartupScript(this, GetType(), "error", "alert('S/L must be less than the buying price.');", true);
                return;
            }
        }
        else //if (validateValue(txtBuySL.Text))
        {
            if (txtBuySL.Text.ToString() != string.Empty)
            {
                ScriptManager.RegisterStartupScript(this, GetType(), "error", "alert('Only positive numbers allowed in S/L!');", true);
                return;
            }
        }

        //Main Logic
        uint current_ShareQuantity;
        if (UInt32.TryParse(txtBuyAvailShareQuantity.Text, out current_ShareQuantity))
        {
            if (current_ShareQuantity > 0)
            {
                SqlConnection transac_con = new SqlConnection(ConfigurationManager.ConnectionStrings[current_connectionString].ConnectionString);
                SqlCommand cmdAddBuyTransac = new SqlCommand("INSERT INTO [Transaction](UserName, GameID, ShareName, TransactionDate, ShareValue, ShareQuantity, TransactionType, ShareTP, ShareSL)" +
                                                                "values('" + current_username + "','" + current_gameid + "', '" + current_ShareSymbol + "', (SELECT CONVERT(VARCHAR, GameElapsedDate, 101) AS GameElapsedDate FRom Game WHERE GameID=" + current_gameid + "),'" +
                                                                current_MarketShareValue + "','" + current_ShareQuantity + "','" + current_TransactionType + "','" + current_TP + "','" + current_SL + "')", transac_con);

                SqlCommand cmdSelectCurrID = new SqlCommand("SELECT MAX(TransactionID) AS CurrID FROM [Transaction]", transac_con);
                SqlCommand cmdGetUserAcctAmt = new SqlCommand("SELECT AccountAmount FROM [User] WHERE UserName = @current_user", transac_con);
                SqlCommand cmdUpdateUserAcctAmt = new SqlCommand("UPDATE [User] SET AccountAmount = @afterBought_amt WHERE UserName = @current_user", transac_con);

                cmdGetUserAcctAmt.Parameters.Add("@current_user", SqlDbType.VarChar).Value = current_username;
                cmdUpdateUserAcctAmt.Parameters.Add("@current_user", SqlDbType.VarChar).Value = current_username;

                transac_con.Open(); // open for data reader
                
                //get account amount from user database first
                cmdGetUserAcctAmt.ExecuteScalar();
                SqlDataReader myGetUserAcctAmtReader = cmdGetUserAcctAmt.ExecuteReader();
                double current_UserAcctAmt = 0;
                while (myGetUserAcctAmtReader.Read())
                {
                    double.TryParse(myGetUserAcctAmtReader["AccountAmount"].ToString(), out current_UserAcctAmt);
                }
                transac_con.Close(); // close for data reader

                // check if user enough money to buy that quantity of stocks
                if (current_UserAcctAmt > (current_ShareQuantity * current_MarketShareValue))
                {
                    transac_con.Open();

                    cmdAddBuyTransac.ExecuteNonQuery();
                    current_ID = Int32.Parse(cmdSelectCurrID.ExecuteScalar().ToString());

                    cmdUpdateUserAcctAmt.Parameters.Add("@afterBought_amt", SqlDbType.Float).Value = current_UserAcctAmt - Convert.ToDouble(current_ShareQuantity * current_MarketShareValue);
                    cmdUpdateUserAcctAmt.ExecuteNonQuery();

                    SqlCommand cmdAddintoUCS = new SqlCommand("INSERT INTO [UserCurrentStock](TransactionID, GameID, UserName, ShareName, ShareValue, ShareQuantity, ShareTP, ShareSL)" +
                                                                "values('" + current_ID + "','" + current_gameid + "','" + current_username + "','" + current_ShareSymbol + "','" +
                                                                current_MarketShareValue + "','" + current_ShareQuantity + "','" + current_TP + "','" + current_SL + "')", transac_con);

                    cmdAddintoUCS.ExecuteNonQuery();
                    bindgrid_Transaction();
                    transac_con.Close();
                    successfulTransac = true;
                }
                else
                {
                    ScriptManager.RegisterStartupScript(this, GetType(), "error", "alert('You do not have enough cash to buy so much!');", true);
                    transac_con.Close();
                }
                transac_con.Close();
            }
            else //if (current_ShareQuantity > 0)
            {
                ScriptManager.RegisterStartupScript(this, GetType(), "error", "alert('You cannot have 0 quantity!');", true);
            }
        }
        else //if (UInt32.TryParse(txtBuyAvailShareQuantity.Text, out current_ShareQuantity))
        {
            ScriptManager.RegisterStartupScript(this, GetType(), "error", "alert('Please enter numeric values.');", true);
        }

        if (successfulTransac)
            Response.Redirect(Request.RawUrl);
    }

    //GridView that display the stocks that the user have for a quick buy
    protected void GridView_UserExistingStock_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        if (!ClientScript.IsStartupScriptRegistered("graph"))
        {
            Page.ClientScript.RegisterStartupScript(this.GetType(), "graph", "drawGraph();", true);
        }

        string currentCommand = e.CommandName;
        int currentRowIndex = Int32.Parse(e.CommandArgument.ToString());
        double current_MarketShareValue = Convert.ToDouble(GridView_UserExistingStock.Rows[currentRowIndex].Cells[2].Text);
        string current_TransactionType = "BUY";
        int current_ID = 0;
        bool successfulTransac = false;
        double current_TP = -1;
        double current_SL = -1;

        if (currentCommand == "BuyStock")
        {
            uint current_ShareQuantity;
            if (UInt32.TryParse(txt_QtyUserExisitingStock.Text, out current_ShareQuantity))
            {
                if (current_ShareQuantity > 0)
                {
                    string current_ShareSymbol = GridView_UserExistingStock.Rows[currentRowIndex].Cells[1].Text;

                    SqlConnection transac_con = new SqlConnection(ConfigurationManager.ConnectionStrings[current_connectionString].ConnectionString);

                    SqlCommand cmdAddBuy = new SqlCommand("INSERT INTO [Transaction](UserName, GameID, ShareName, TransactionDate, ShareValue, ShareQuantity, TransactionType, ShareTP, ShareSL)" +
                                                          "values('" + current_username + "','" + current_gameid + "', '" + current_ShareSymbol + "', (SELECT CONVERT(VARCHAR, GameElapsedDate, 101) AS GameElapsedDate FRom Game WHERE GameID=" + current_gameid + "),'" +
                                                          current_MarketShareValue + "','" + current_ShareQuantity + "','" + current_TransactionType + "','" + current_TP + "','" + current_SL + "')", transac_con);

                    SqlCommand cmdSelectCurrID = new SqlCommand("SELECT MAX(TransactionID) AS CurrID FROM [Transaction]", transac_con);

                    SqlCommand cmdGetUserAcctAmt = new SqlCommand("SELECT AccountAmount FROM [User] WHERE UserName = @current_user", transac_con);
                    cmdGetUserAcctAmt.Parameters.Add("@current_user", SqlDbType.VarChar).Value = current_username;
                    
                    SqlCommand cmdUpdateUserAcctAmt = new SqlCommand("UPDATE [User] SET AccountAmount = @afterBought_amt WHERE UserName = @current_user", transac_con);
                    cmdUpdateUserAcctAmt.Parameters.Add("@current_user", SqlDbType.VarChar).Value = current_username;

                    transac_con.Open(); //open for data reader

                    //get account amount from database first
                    cmdGetUserAcctAmt.ExecuteScalar();
                    SqlDataReader myGetUserAcctAmtReader = cmdGetUserAcctAmt.ExecuteReader();
                    double current_UserAcctAmt = 0;
                    while (myGetUserAcctAmtReader.Read())
                    {
                        double.TryParse(myGetUserAcctAmtReader["AccountAmount"].ToString(), out current_UserAcctAmt);
                    }
                    transac_con.Close();

                    // check if user enough money to buy that quantity of stocks
                    if (current_UserAcctAmt > (current_ShareQuantity * current_MarketShareValue))
                    {
                        transac_con.Open();
                        cmdAddBuy.ExecuteNonQuery();

                        cmdUpdateUserAcctAmt.Parameters.Add("@afterBought_amt", SqlDbType.Float).Value = current_UserAcctAmt - (current_ShareQuantity * current_MarketShareValue);
                        cmdUpdateUserAcctAmt.ExecuteNonQuery();

                        current_ID = Int32.Parse(cmdSelectCurrID.ExecuteScalar().ToString());
                        SqlCommand cmdAddintoUCS = new SqlCommand("INSERT INTO [UserCurrentStock](TransactionID, GameID, UserName, ShareName, ShareValue, ShareQuantity, ShareTP, ShareSL)" +
                                                                  "values('" + current_ID + "','" + current_gameid + "','" + current_username + "','" + current_ShareSymbol + "','" +
                                                                  current_MarketShareValue + "','" + current_ShareQuantity + "','" + current_TP + "','" + current_SL + "')", transac_con);

                        cmdAddintoUCS.ExecuteNonQuery();
                        bindgrid_Transaction();
                        transac_con.Close();
                        successfulTransac = true;
                    }
                    else //if (current_UserAcctAmt > (current_ShareQuantity * current_ShareValue))
                    {
                        ScriptManager.RegisterStartupScript(this, GetType(), "error", "alert('You do not have enough cash to buy so much!');", true);
                        transac_con.Close();
                    }
                }
                else //if (current_ShareQuantity > 0)
                {
                    ScriptManager.RegisterStartupScript(this, GetType(), "error", "alert('You cannot have 0 quantity!');", true);
                }
            }
            else //if (UInt32.TryParse(txt_QtyUserExisitingStock.Text, out current_ShareQuantity))
            {
                ScriptManager.RegisterStartupScript(this, GetType(), "error", "alert('Please enter numeric values.');", true);
            }
        }//if (currentCommand == "BuyStock")
        
        if (successfulTransac)
            Response.Redirect(Request.RawUrl);
    }

    //Grid view for displaying the current stock that the user have in the market
    //User also able to sell through this grid view.
    protected void GridView_SellStock_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        if (!ClientScript.IsStartupScriptRegistered("graph"))
        {
            Page.ClientScript.RegisterStartupScript(this.GetType(), "graph", "drawGraph();", true);
        }

        string currentCommand = e.CommandName;
        int currentRowIndex = Int32.Parse(e.CommandArgument.ToString());
        double current_MarketShareValue = 0;

        if (currentCommand == "SellStock")
        {
            uint user_SellingQty;

            if (UInt32.TryParse(txtSellShareQuantity.Text, out user_SellingQty))
            {
                if (user_SellingQty > 0)
                {
                    string current_RelatedTransactionID = GridView_SellStock.Rows[currentRowIndex].Cells[0].Text;
                    string current_ShareSymbol = GridView_SellStock.Rows[currentRowIndex].Cells[3].Text;
                    double UserBoughtShareValue = Convert.ToDouble(GridView_SellStock.Rows[currentRowIndex].Cells[5].Text);
                    int UserBoughtQty = Int32.Parse(GridView_SellStock.Rows[currentRowIndex].Cells[7].Text);
                    double userAmt = 0.0;

                    int current_Qty = UserBoughtQty - Convert.ToInt32(user_SellingQty);
                    if (current_Qty >= 0)
                    {
                        current_MarketShareValue = getRates(current_gameid, current_ShareSymbol);

                        SqlConnection transac_con = new SqlConnection(ConfigurationManager.ConnectionStrings[current_connectionString].ConnectionString);

                        SqlCommand cmdAddSell = new SqlCommand("INSERT INTO [Transaction](UserName, GameID, ShareName, TransactionDate, ShareValue, ShareQuantity, TransactionType, RelatedTransactionID)" +
                                                               "values('" + current_username + "','" + current_gameid + "', '" + current_ShareSymbol + "', (SELECT CONVERT(VARCHAR, GameElapsedDate, 101) AS GameElapsedDate FRom Game WHERE GameID=" + current_gameid + "),'" +
                                                               current_MarketShareValue + "','" + user_SellingQty + "', 'SELL','" + current_RelatedTransactionID + "')", transac_con);

                        SqlCommand cmdUpdateUserQty = new SqlCommand("UPDATE [UserCurrentStock] SET ShareQuantity = @current_qty WHERE TransactionID = @SE_transactionID", transac_con);

                        SqlCommand cmdSelectUserAmt = new SqlCommand("SELECT AccountAmount FROM [User] WHERE UserName = @current_user", transac_con);

                        SqlCommand cmdUpdateUserAcctAmt = new SqlCommand("UPDATE [User] SET AccountAmount = @calculated_amt WHERE UserName = @current_user", transac_con);

                        SqlCommand cmdDeleteZeroStock = new SqlCommand("DELETE FROM UserCurrentStock WHERE (TransactionID = @transactionID)", transac_con);

                        cmdUpdateUserQty.Parameters.Add("@SE_transactionID", SqlDbType.Int).Value = current_RelatedTransactionID;
                        cmdUpdateUserQty.Parameters.Add("@current_qty", SqlDbType.Int).Value = current_Qty;
                        cmdSelectUserAmt.Parameters.Add("@current_user", SqlDbType.VarChar).Value = current_username;
                        cmdUpdateUserAcctAmt.Parameters.Add("@current_user", SqlDbType.VarChar).Value = current_username;
                        cmdDeleteZeroStock.Parameters.Add("@transactionID", SqlDbType.Int).Value = current_RelatedTransactionID;

                        transac_con.Open();
                        cmdAddSell.ExecuteNonQuery();
                        cmdUpdateUserQty.ExecuteNonQuery();
                        userAmt = Convert.ToDouble(cmdSelectUserAmt.ExecuteScalar());

                        //Base amount + Profit
                        double calulated_amt = (userAmt + (current_MarketShareValue * user_SellingQty));
                        cmdUpdateUserAcctAmt.Parameters.Add("@calculated_amt", SqlDbType.Float).Value = (calulated_amt);
                        cmdUpdateUserAcctAmt.ExecuteNonQuery();

                        if (current_Qty == 0)
                        {
                            cmdDeleteZeroStock.ExecuteNonQuery();
                        }

                        bindgrid_Transaction();
                        transac_con.Close();

                        Response.Redirect(Request.RawUrl);
                    }
                    else //if (current_Qty >= 0)
                    {
                        ScriptManager.RegisterStartupScript(this, GetType(), "error", "alert('Unable to sell, Please contact administrator.');", true);
                    }
                }
                else //if (user_SellingQty > 0) = False
                {
                    ScriptManager.RegisterStartupScript(this, GetType(), "error", "alert('You cannot sell 0 quantity!');", true);
                }
            }
            else //if (UInt32.TryParse(txtSellShareQuantity.Text, out user_SellingQty))
            {
                ScriptManager.RegisterStartupScript(this, GetType(), "error", "alert('Please enter numeric values.');", true);
            }
        } //if (currentCommand == "SellStock")
    }

    //data bind after updated records
    protected void GridView_EditTPSL_RowUpdated(object sender, GridViewUpdatedEventArgs e)
    {
        if (!ClientScript.IsStartupScriptRegistered("graph"))
        {
            Page.ClientScript.RegisterStartupScript(this.GetType(), "graph", "drawGraph();", true);
        }

        bindgrid_Transaction();
    }

    //DataBind for GridViews
    public void bindgrid_Transaction()
    {
        SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings[current_connectionString].ConnectionString);
        SqlCommand cmd = new SqlCommand("Select * from [Transaction]", con);
        con.Open();
        SqlDataAdapter da = new SqlDataAdapter(cmd);
        DataSet ds = new DataSet();
        da.Fill(ds);
        cmd.ExecuteScalar();

        GridView_UserExistingStock.DataBind();
        GridView_SellStock.DataBind();
        con.Close();
    }

    //validation for TP/SL
    public bool validateValue(string Input)
    {
        double correctValue;
        if (double.TryParse(Input, out correctValue))
        {
            if (correctValue >= 0)
            {
                return true;
            }
        }
        return false;
    }

    //getting Live Rates
    public double getRates(int selected_GID, string selected_StockSymbol)
    {
        double rates = 0;

        SqlConnection rates_con = new SqlConnection(ConfigurationManager.ConnectionStrings[current_connectionString].ConnectionString);
        SqlCommand cmdGetRates = new SqlCommand("SELECT ShareSimulation.CloseValue FROM Game " +
                                                "INNER JOIN ShareSimulation ON Game.GameID = ShareSimulation.GameID " + 
                                                "AND Game.GameElapsedDate = ShareSimulation.HistoryDate " +
                                                "WHERE (ShareSimulation.ShareSymbol = @sharesymbol) AND (Game.GameID = @gameID)", rates_con);
        
        cmdGetRates.Parameters.Add("@sharesymbol", SqlDbType.VarChar).Value = selected_StockSymbol;
        cmdGetRates.Parameters.Add("@gameid", SqlDbType.Int).Value = selected_GID;

        rates_con.Open();

        bool res = false;

        if (cmdGetRates.ExecuteScalar() != null)
            res = Double.TryParse(cmdGetRates.ExecuteScalar().ToString(), out rates);

        if(res == false)
            rates = 0;

            rates_con.Close();

        return rates;
    }

    //changes of drop down list for buy available
    protected void DropDownList_AvailableStock_SelectedIndexChanged(object sender, EventArgs e)
    {
        if (ShareCompanyDropdown.SelectedIndex != 0)
        {
            if (!ClientScript.IsStartupScriptRegistered("graph"))
            {
                Page.ClientScript.RegisterStartupScript(this.GetType(), "graph", "drawGraph();", true);
            }

            Timer1.Interval = 5 * 1000;
            Timer1.Enabled = true;
            

            SqlConnection user_con = new SqlConnection(ConfigurationManager.ConnectionStrings[current_connectionString].ConnectionString);
            SqlCommand cmdRetrieveGame_ID = new SqlCommand("SELECT GameID FROM [GameUsers] WHERE UserName = @username", user_con);
            cmdRetrieveGame_ID.Parameters.Add("@username", SqlDbType.VarChar).Value = current_username;

            user_con.Open();
            cmdRetrieveGame_ID.ExecuteNonQuery();
            SqlDataReader myGameIDReader = cmdRetrieveGame_ID.ExecuteReader();
            while (myGameIDReader.Read())
            {
                current_gameid = Int32.Parse(myGameIDReader["GameID"].ToString());
            }
            user_con.Close();

            string stockSymbol = ShareCompanyDropdown.SelectedValue;
            lblRates.Text = Convert.ToString(getRates(current_gameid, stockSymbol));
        }
    }

    protected void GraphType_Radio_SelectedIndexChanged(object sender, EventArgs e)
    {
        if (!ClientScript.IsStartupScriptRegistered("graph"))
        {
            Page.ClientScript.RegisterStartupScript(this.GetType(), "graph", "drawGraph();", true);
        }
    }

    protected void Duration_Radio_SelectedIndexChanged(object sender, EventArgs e)
    {
        if (!ClientScript.IsStartupScriptRegistered("graph"))
        {
            Page.ClientScript.RegisterStartupScript(this.GetType(), "graph", "drawGraph();", true);
        }
    }

    protected void DropDownList_SelectedStock_SelectedIndexChanged(object sender, EventArgs e)
    {
        if (!ClientScript.IsStartupScriptRegistered("graph"))
        {
            Page.ClientScript.RegisterStartupScript(this.GetType(), "graph", "drawGraph();", true);
        }
    }
}                                             
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        